package com.demo.server.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo.server.constant.CommonConstant;
import com.demo.server.entity.Hospital;
import com.demo.server.entity.dto.HospitalDto;
import com.demo.server.entity.req.HospitalSearchReq;
import com.demo.server.mapper.HospitalMapper;
import com.demo.server.util.Result;
import com.demo.server.util.ResultPage;
import com.demo.server.util.UUIDUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service
public class HospitalService {
	
	@Autowired
	HospitalMapper hospitalMapper;
	
	/**
	 * @title 查询医院
	 * @param req
	 * @return
	 */
	public ResultPage<Hospital> search(HospitalSearchReq req) {
		Page<Object> page = PageHelper.startPage(req.getPage(), req.getSize());
		HospitalDto dto = new HospitalDto();
		BeanUtils.copyProperties(req, dto);
		List<Hospital> hospitals = hospitalMapper.select(dto);
		return ResultPage.success(hospitals, page.getTotal());
	}
	
	/**
	 * @title 添加医院
	 * @param req
	 * @return
	 */
	public Result add(Hospital req) {
		Date date = new Date();
		Hospital record = hospitalMapper.selectByCode(req.getCode());
		if(record != null) {
			return Result.fail("医院编码已存在");
		}
		req.setCode(req.getCode());
		req.setId(UUIDUtil.get32UUID());
		req.setCreatetime(date);
		hospitalMapper.insertSelective(req);
		return Result.success();
	}
	
	/**
	 * @title 修改医院
	 * @param req
	 * @return
	 */
	public Result edit(Hospital req) {
		Date date = new Date();
		if(StringUtils.isEmpty(req.getId())) {
			return Result.fail(CommonConstant.LACK_PARAM);
		}
		req.setCode(null); //编码不可修改
		req.setModifytime(date);
		hospitalMapper.updateByPrimaryKeySelective(req);
		return Result.success();
	}
	
	/**
	 * @title 删除医院
	 * @param id
	 * @return
	 */
	public Result delete(String id) {
		hospitalMapper.deleteByPrimaryKey(id);
		return Result.success();
	}

}
